package com.kqb.sgadmin.service.impl;

import cn.dev33.satoken.stp.SaTokenInfo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.kqb.sgadmin.mapper.AdminMapper;
import com.kqb.sgadmin.model.Admin;
import com.kqb.sgadmin.model.dto.admin.AdminLoginDTO;
import com.kqb.sgadmin.service.AdminService;
import com.kqb.sgadmin.utils.PwdUtils;
import com.kqb.sgcommon.base.exception.BusinessException;
import com.kqb.sgcommon.base.utils.ThrowUtils;
import com.kqb.sgcommon.satoken.Device;
import com.kqb.sgcommon.satoken.StpKit;
import org.springframework.stereotype.Service;

/**
 * @author D
 * @description 针对表【t_admin(管理员表)】的数据库操作Service实现
 * @createDate 2025-06-16 14:14:59
 */
@Service
public class AdminServiceImpl extends ServiceImpl<AdminMapper, Admin>
        implements AdminService {

    @Override
    public boolean isExist(String username, String phone) {
        QueryWrapper<Admin> qw = new QueryWrapper<Admin>()
                .eq("username", username)
                .or()
                .eq("phone", phone);
        return this.exists(qw);
    }

    @Override
    public SaTokenInfo login(AdminLoginDTO adminLoginDTO) {
        String username = adminLoginDTO.getUsername();
        String password = adminLoginDTO.getPassword();
        Admin oldAdmin = this.baseMapper.selectOne(new QueryWrapper<Admin>()
                .eq("username", username));
        if (oldAdmin == null) {
            throw new BusinessException("用户不存在");
        }
        boolean res = PwdUtils.checkPwd(password, oldAdmin.getPassword());
        ThrowUtils.throwNotIf(res, BusinessException.of("密码错误"));
        StpKit.ADMIN.login(oldAdmin.getId(), Device.PC);
        return StpKit.ADMIN.getTokenInfo();
    }
}




